import time
import win32api
import win32con
import threading
import win32clipboard
from aip import AipOcr
from PIL import ImageGrab


def checkClipBoard():
    start = time.time()
    while True:
        img = ImageGrab.grabclipboard()
        if img:
            break
        else:
            time.sleep(1)
        if (time.time() - start) > 10:
            break


def screenShot():
    win32clipboard.OpenClipboard()
    win32clipboard.EmptyClipboard()
    win32clipboard.CloseClipboard()
    try:
        win32api.keybd_event(0x5B, 0, 0, 0)  # 0x5B --> left win key
        win32api.keybd_event(0x10, 0, 0, 0)  # 0x10 --> SHIFT
        win32api.keybd_event(0x53, 0, 0, 0)  # 0x53 --> S
        win32api.keybd_event(0x5B, 0, win32con.KEYEVENTF_KEYUP, 0)
        win32api.keybd_event(0x10, 0, win32con.KEYEVENTF_KEYUP, 0)
        win32api.keybd_event(0x53, 0, win32con.KEYEVENTF_KEYUP, 0)
    except Exception as e:
        print('Keyboard event fail: {}', e)
        return
    t = threading.Thread(target=checkClipBoard)
    t.setDaemon(True)
    t.start()
    t.join()
    image = ImageGrab.grabclipboard()
    if image is None:
        pass
    else:
        image.save('./capture.png')


def bdOCR(keyword, account):
    APP_ID, API_KEY, SECRET_KEY = account
    aipOCR = AipOcr(APP_ID, API_KEY, SECRET_KEY)
    with open('./capture.png', 'rb') as f:
        img = f.read()
    f.close()
    if keyword == 1:
        getResult = aipOCR.basicAccurate(img)
    else:
        getResult = aipOCR.basicGeneral(img)
    txtResult = ''
    for item in getResult['words_result']:
        txtResult += item['words'] + '\n'

    win32clipboard.OpenClipboard()
    win32clipboard.EmptyClipboard()
    win32clipboard.SetClipboardText(txtResult)
    win32clipboard.CloseClipboard()


# main()
